<?php defined('SYSPATH') or die('No direct script access.');

class Common_Controller extends Controller 
{
	function setlang($lang)
    {
	    // Array of allowed languages
	    $locales = Config::item('locale.allowed_locales');
		
        // Store locale config values
	    Config::set('locale.lang', $lang);
	    Config::set('locale.language', $locales[$lang]);
	
	    // Overwrite setlocale which has already been set before in Kohana::setup()
	    setlocale(LC_ALL, Config::item('locale.language').'.UTF-8');
	
	    // Finally set a language cookie for 6 months
	    cookie::set('lang', $lang, 15768000);
		
		$url = '';
		
		if(isset($_SERVER['HTTP_REFERER']))
		{
			$referer =  $_SERVER['HTTP_REFERER'];
			
			$purl = parse_url($referer);
			
			//var_dump(parse_url($referer));
			
			preg_match('~^[a-z]{2}(?=/|$)~i', substr($purl['path'], 1), $matches);
			$old_lang = isset($matches[0]) ? strtolower($matches[0]) : Config::item('multi_lang.fallback_language');
			
			$uri = substr($purl['path'], 4);
		
			$url = $purl['scheme'].'://'.$purl['host'].'/'.$lang.'/'.$uri;
		}
		else
		{
			$url = '';
		}
		
		url::redirect($url, 301);
    }
}
